package com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer;

import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.lancoo.znbkxx.teacher.R;
import com.lancoo.znbkxx.teacher.widget.BamImageView;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * auther: 王国龙
 * Date：音频播放器
 * describe:
 */
public class AudioPlayer extends MediaPlayer{

    private SimpleDateFormat format;
    private Timer timer;
    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    private int currentPosition;//当前音乐播放的进度

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private AppCompatActivity activity;
    private BamImageView play_pause;
    private TextView  musicLength, musicCur;
    private SeekBar seekBar;

    private boolean isHaveChildAudio = true;
    public static ParentAudioListener mParentAudioListener;
    public interface ParentAudioListener{
        void onStopChildAudioPlayer();
    }

    public AudioPlayer(AppCompatActivity activity,
                       BamImageView play_pause,
                       SeekBar seekBar, TextView musicCur, TextView musicLength,
                       String audioUrl,
                       ParentAudioListener parentAudioListener){
        this.activity = activity;
        this.play_pause = play_pause;
        this.seekBar = seekBar;
        this.musicLength = musicLength;
        this.musicCur = musicCur;
        this.mParentAudioListener = parentAudioListener;

        format = new SimpleDateFormat("mm:ss");

//        play_pause.setImageResource(R.drawable.aibk_anim_loading);
        initMediaPlayer(audioUrl);//初始化mediaplayer
    }

    public AudioPlayer(AppCompatActivity activity,
                       BamImageView play_pause,
                       SeekBar seekBar, TextView musicCur, TextView musicLength,
                       String audioUrl){
        this.activity = activity;
        this.play_pause = play_pause;
        this.seekBar = seekBar;
        this.musicLength = musicLength;
        this.musicCur = musicCur;

        isHaveChildAudio = false;

        format = new SimpleDateFormat("mm:ss");

//        play_pause.setImageResource(R.drawable.aibk_anim_loading);
        initMediaPlayer(audioUrl);//初始化mediaplayer

    }

    private void initMediaPlayer(String audioUrl) {
        try {
            seekBar.setOnSeekBarChangeListener(new MySeekBar());
            mediaPlayer.setDataSource(audioUrl);//指定音频文件的路径
            mediaPlayer.prepareAsync();//让mediaplayer进入准备状态
            mediaPlayer.setLooping(false);//关闭循环播放
            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    seekBar.setMax(mediaPlayer.getDuration());
                    musicLength.setText(format.format(mediaPlayer.getDuration()));
                    musicCur.setText("00:00");
                    play_pause.setClickable(true);
                    play_pause.performClick();
                }
            });
            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    currentPosition = 0;
                    mediaPlayer.seekTo(0);
                    musicCur.setText("00:00");
                    play_pause.setImageResource(R.mipmap.aibk_audioplayer_play);
                }
            });
            play_pause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();//开始播放
                        mediaPlayer.seekTo(currentPosition);

                        //监听播放时回调函数
                        timer = new Timer();
                        timer.schedule(new TimerTask() {

                            Runnable updateUI = new Runnable() {
                                @Override
                                public void run() {
                                    if(mediaPlayer!=null&&mediaPlayer.isPlaying()) {
                                        musicCur.setText(format.format(mediaPlayer.getCurrentPosition()) + "");
                                    }
                                }
                            };

                            @Override
                            public void run() {
                                if (!isSeekBarChanging) {
                                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                                    activity.runOnUiThread(updateUI);
                                }
                            }
                        }, 0, 50);
                        play_pause.setImageResource(R.mipmap.aibk_audioplayer_pause);

                        if(isHaveChildAudio) {
                            mParentAudioListener.onStopChildAudioPlayer();
                        }
                    }else{
                        mediaPlayer.pause();//暂停播放
                        currentPosition = seekBar.getProgress();
                        play_pause.setImageResource(R.mipmap.aibk_audioplayer_play);
                    }
                }
            });
            play_pause.setClickable(false);//必须放在setOnClickListener方法之后
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }

    public void DestoryAudio() {
        isSeekBarChanging = true;
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void pauseAudio(){
        if (mediaPlayer != null&&mediaPlayer.isPlaying()) {
            play_pause.performClick();
        }
    }

    public boolean setPlaySpeed(float speed) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                PlaybackParams params = mediaPlayer.getPlaybackParams();
                params.setSpeed(speed);
                mediaPlayer.setPlaybackParams(params);
                return true;
            } catch (Exception e) {
                Log.e("TAG", "setPlaySpeed: ", e);
                return false;
            }
        }
        return false;
    }
}
